﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ForumsBrowser.ObjectGateway;
using ForumsBrowser.BusinessObjects;
using System.Diagnostics;
using System.Collections.ObjectModel;

namespace ForumsBrowser
{
    /// <summary>
    /// Interaction logic for ForumView.xaml
    /// </summary>
    public partial class ForumView : UserControl
    {

        public static readonly DependencyProperty DetailProperty = DependencyProperty.Register("Detail", typeof(bool), typeof(ForumView), new PropertyMetadata(true));

        public bool Detail
        {
            get { return (bool)this.GetValue(DetailProperty); }
            set {
                bool changed = value != Detail;
                this.SetValue(DetailProperty, value);

                if (changed)
                    SetStyle();
            }
        }

        private ObservableCollection<Thread> Threads
        {
            get
            {
                return (ObservableCollection<Thread>)this.Resources["threads"];
            }
        }

        private List<Forum> _currentForums = new List<Forum>();

        public event EventHandler<ThreadSelectedEventArgs> ThreadSelected;
        public event EventHandler<ThreadSelectedEventArgs> ViewLastPost;
        public event EventHandler<ThreadSelectedEventArgs> Browse;


        public ForumView()
        {
            InitializeComponent();
            SetStyle();
        }

        private void SetStyle()
        {
            if (Detail)
            {
                this.listView1.ItemTemplate = (DataTemplate)Resources["DetailedItem"];
            }
            else
            {
                this.listView1.ItemTemplate = (DataTemplate)Resources["SummaryItem"];
            }
        }
        
        public void BindThreads(string forumName, bool clear)
        {
            if (clear)
            {
                this._currentForums.ForEach(f => Gateway.ForumDisableUpdates(f.ShortName));
                this._currentForums.Clear();
                this.Threads.Clear();
            }

            Gateway.ForumEnableUpdates(forumName, ForumUpdates);
        }

        public void BindThreads(IEnumerable<string> forumNames)
        {
            this._currentForums.ForEach(f => Gateway.ForumDisableUpdates(f.ShortName));
            this._currentForums.Clear();
            this.Threads.Clear();
            foreach (string f in forumNames)
                Gateway.ForumEnableUpdates(f, ForumUpdates);
        }

        private void ForumUpdates(object sender, ForumUpdateEventArgs e)
        {
            if (this.Dispatcher.CheckAccess())
            {
                _currentForums.AddUnique(e.Forum);
                
                this.Threads.InsertRangeInOrder(e.Forum.Threads, t => t.LastUpdate, (d1, d2) => -d1.CompareTo(d2));
                var list = e.Forum.Threads.OrderByDescending(t => t.LastUpdate).Where(t => t.Messages.Count > 0).ToList();
                list.ForEach(m => PopupAlert.Show(m, ThreadListItem_ViewPost));
            }
            else
            {
                this.Dispatcher.Invoke(new EventHandler<ForumUpdateEventArgs>(ForumUpdates), sender, e);
            }
        }

        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Thread t = e.AddedItems.OfType<Thread>().FirstOrDefault();
            var del = ThreadSelected;
            if (del != null && t != null)
                del(this, new ThreadSelectedEventArgs { Thread = t });

        }

        private void ThreadListItem_Browse(object sender, ThreadSelectedEventArgs e)
        {
            var handler = this.Browse;
            if (handler != null)
                handler(sender, e);
        }

        private void ThreadListItem_ViewLastPost(object sender, ThreadSelectedEventArgs e)
        {
            var handler = this.ViewLastPost;
            if (handler != null)
                handler(sender, e);
        }

        private void ThreadListItem_ViewPost(object sender, ThreadSelectedEventArgs e)
        {
            var del = ThreadSelected;
            if (del != null)
                del(this, e);
            //Detail = !Detail;
            //SetStyle();
        }
    }

    public class ThreadList : ObservableCollection<Thread> { }
}
